<?php

/*
 * Отвечает за извлечение, создание, сохранение и удаление узлов.
 * За провизводные узлов (конфигурации) отвечают другие контроллеры
 */

class Admin_TreeNodeController extends Zend_Rest_Controller{
    private $_mapperTree;
    private $_mapperHtaccess;
    public function init(){
        parent::init();
        $this->getHelper('layout')->setLayout('admin');
        $this->_mapperTree = new Admin_Model_TreeNodeMapper();
        $this->_mapperHtaccess = new Admin_Model_HtaccessMapper();
    }
    
    public function indexAction(){
    	echo "index"; 
    	exit;
    }
    
    public function getAction(){
    	$req = $this->getRequest();
    	$node = null;
    	
    	if(($id = (int)$req->getParam('id',0))>0)
    	{
			$node = $this->_mapperTree->find($id);
		}
    	/*elseif(1==$req->getParam('r',0))
    	{
    		//not used
    		$node = $m->findRoot(true);
    	}*/
    	$this->_helper->json ( $node );
    }
    public function postAction(){
    	$request = $this->getRequest();
        $list = $request->getParam('list',null);
        if (null==$list) $list = array($request->getParams());
        elseif (!is_array($list))
            throw new Zend_Exception("param list must be an array");
        $form = new Admin_Form_Node();
        $result = array();
        foreach($list as $params){
            $parentId = isset($params['pId'])?(int)$params['pId']:0;
            if ($parentId<1) throw new Zend_Exception ("pId wasn't specified");
    		if (!$form->isValid($params)){
                if (count($result)==0)
                    $result = array('success'=>false, 'msg'=>'Данные некорректны');
                else
                    $result[] = array('success'=>false, 'msg'=>'Данные некорректны');
                $this->_helper->json($result);
                return;
            }
	    	$val = $form->getValidValues($params);
	    	$node = new Admin_Model_TreeNode($val);
	    	$node->setInMenu(isset($params['InMenu'])? 1 : 0);
	    	$this->_mapperTree->addSubNode($parentId,$node);
            $r = array('success'=>true, 'msg'=>'Узел добавлен',
                'node' => array(
                    'id'=>$node->getId(),
                    'href'=>'#'.$node->getId(),
                    'text'=>$node->getName(),
                    'leaf'=>true
                )
            );
            if (count($list)==1) $result = $r; else $result[] = $r;
        }
        $this->_mapperHtaccess->RefreshUrl($this->_mapperTree->fetchURLs());
    	$this->_helper->json($result);
    }
    public function putAction(){
    	$request = $this->getRequest();
    	parse_str($request->getRawBody(),$params);
    	$id = (int)$params['id'];
    	if ($id>0)
    	{
    		$form = new Admin_Form_Node();
    		if ($form->isValid($params))
    		{
	    		//$params['InMenu'] = isset($params['InMenu'])? 1 : 0;
	    		$val = $form->getValidValues($params);
	    		$node = new Admin_Model_TreeNode($val);
	    		$node->setId($id);
	    		$this->_mapperTree->save($node,$val);
                $this->_mapperHtaccess->RefreshUrl($this->_mapperTree->fetchURLs());
	    		$result = array('success'=>true, 'msg'=>'Узел сохранен',
                    'node' => array(
                        'id'=>$node->getId(),
                        'href'=>'#'.$node->getId(),
                        'text'=>$node->getName()
                        //,'leaf'=>true
                    )
                );
    		}
    		else
    			$result = array('success'=>false, 'msg'=>'Данные некорректны');
    	}
    	else
    		$result = array('success'=>false, 'msg'=>'Не установлен id');
	    $this->_helper->json($result);
    }    
    
	public function deleteAction(){
    	$id = (int)$this->getRequest()->getParam('id',0);
        if ($id==0){
            $this->_helper->json(array('success'=>false, 'msg'=>'Узел не удален: не задан id'));
            return;
        }
    	if ($this->_mapperTree->delete($id)>0){
            $this->_mapperHtaccess->RefreshUrl($this->_mapperTree->fetchURLs());
            $this->_helper->json(array('success'=>true, 'msg'=>'Узел удален', 'id'=>$id) );
        }
    	$this->_helper->json(array('success'=>false, 'msg'=>'Узел не найден'));
    }
}

